<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @sort-change="sortChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">

      <template #menu-form-before="{}">
        <el-link v-if="this.website" :href="this.website" type="primary" target="_blank" style="position: absolute;left: 30px;top: 15px;">接码网站: {{ this.website }}</el-link>
      </template>

      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   effect="dark"
                   v-if="permission.service_config_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-divider direction="vertical" />
        <el-button color="#626aef"
                   icon="el-icon-setting"
                   effect="dark"
                   v-if="permission.service_config_mapping"
                   @click="handleMapping">映射配置
        </el-button>
        <el-button type="warning"
                   icon="el-icon-price-tag"
                   effect="dark"
                   v-if="permission.service_config_price"
                   @click="handlePrice">价格查询
        </el-button>
        <el-button color="#E74C3C"
                   effect="dark"
                   v-if="permission.service_config_top"
                   @click="handleTop">
          <i class="iconfont bizicon-remen el-icon--left" />
          TOP/热门国家
        </el-button>
      </template>

      <template #menu="scope">
        <el-button type="primary"
                   text
                   icon="el-icon-setting"
                   v-if="permission.service_config_task"
                   @click.stop="rowTaskOption(scope.row)">任务配置
        </el-button>
        <el-button type="primary"
                   text
                   icon="el-icon-data-board"
                   v-if="permission.service_config_monitor"
                   @click.stop="rowMonitor(scope.row)">实时监控
        </el-button>
      </template>

      <template #serviceApiId="{ row }">
        <el-tag>{{ row.$serviceApiId }}</el-tag>
      </template>
      <template #account="{ row }">
        <el-tooltip v-if="row.apiKey" :content="row.apiKey" placement="bottom">
          <el-text truncated>{{ row.apiKey }}</el-text>
        </el-tooltip>
        <el-tooltip v-else :content="row.username + '|' + row.password" placement="bottom">
          <el-text truncated>{{ row.username + '|' + row.password }}</el-text>
        </el-tooltip>
      </template>
      <template #createUser="{ row }">
        <el-tag>{{ row.createUserName }}</el-tag>
      </template>
      <template #balance="{ row }">
        <el-text v-if="row.balance" size="small">{{ row.balance }}</el-text>
        <el-divider direction="vertical" />
        <el-button :loading="balanceLoading" type="danger" size="small" link @click="rowBalance(row)">查询</el-button>
      </template>
      <template #status="{ row }">
        <el-tag :type="type.enable_disable[row.status]" effect="dark">{{ row.$status }}</el-tag>
      </template>
    </avue-crud>

    <el-dialog
      v-model="mappingBox"
      append-to-body
      destroy-on-close
      draggable
      title="映射配置"
      width="80%"
      align-center>
      <serviceCountryMapping ref="mappingRef" :service-api-id="serviceApiId" :serviceConfigId="serviceConfigId" />
    </el-dialog>

    <el-dialog
      v-model="taskOptionBox"
      append-to-body
      destroy-on-close
      title="任务配置"
      fullscreen
      align-center>
      <serviceTask ref="taskOptionRef" :service-api-id="serviceApiId" :serviceConfigId="serviceConfigId" />
    </el-dialog>

    <el-dialog
      v-model="priceBox"
      append-to-body
      destroy-on-close
      draggable
      :close-on-click-modal="false"
      title="价格列表"
      width="60%"
      align-center>
      <el-table :data="priceData" border row-key="id" default-expand-all max-height="600">
        <el-table-column type="index" align="center" />
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="country" label="国家" align="center" />
        <el-table-column prop="operator" label="运营商" align="center" />
        <el-table-column prop="price" label="价格" align="center" sortable  :sort-method="(a, b) => a.price - b.price" />
        <el-table-column prop="currency" label="货币" align="center" />
        <el-table-column prop="count" label="数量" align="center" />
        <el-table-column prop="rate" label="比例" align="center" />
      </el-table>
    </el-dialog>

    <el-dialog
      v-model="topBox"
      append-to-body
      destroy-on-close
      draggable
      :close-on-click-modal="false"
      title="TOP/热门国家 列表"
      align-center>
      <el-table :data="topData" border>
        <el-table-column type="index" align="center" />
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="country" label="国家" align="center" />
        <el-table-column prop="share" label="购买量比例" align="center" />
        <el-table-column prop="rate" label="激活比例" align="center" />
      </el-table>
    </el-dialog>

    <el-dialog
      v-model="monitorBox"
      append-to-body
      destroy-on-close
      draggable
      :close-on-click-modal="false"
      title="实时监控"
      width="60%"
      align-center>
      <monitor :serviceConfigId="this.serviceConfigId"></monitor>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, balanceApi, priceApi, topApi } from '@/api/sms/service-config';
import { getApiOption } from '@/api/sms/service-api';
import option from '@/option/sms/service-config';
import serviceCountryMapping from '@/views/sms/service-country-mapping.vue';
import serviceTask from '@/views/whatsapp/service-task.vue';
import monitor from '@/views/plugin/websocket/wa-monitor.vue';
import { mapGetters } from 'vuex';
import func from '@/utils/func';
import type from '@/const/tag/type';

export default {
  data() {
    return {
      website: '',
      mappingBox: false,
      taskOptionBox: false,
      priceBox: false,
      topBox: false,
      monitorBox: false,
      serviceConfigId: undefined,
      serviceApiId: undefined,
      balanceLoading: false,
      priceData: [],
      topData: [],
      form: {},
      query: {},
      sort: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: []
    };
  },
  components: {
    serviceCountryMapping,
    serviceTask,
    monitor
  },
  computed: {
    type() {
      return type;
    },
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.service_config_add, false),
        viewBtn: this.validData(this.permission.service_config_view, false),
        delBtn: this.validData(this.permission.service_config_delete, false),
        editBtn: this.validData(this.permission.service_config_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.sort.ascs = 'create_time';
    this.findObject(this.option.column, 'serviceApiId').onChange = ({ value }) => {
      if (value) {
        getApiOption(value).then(res => {
          this.website = res.data.data.website;
        });
      }
    };
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      let serviceApiIdOption = this.findObject(this.option.column, 'serviceApiId');
      if (['edit', 'view'].includes(type)) {
        serviceApiIdOption.disabled = true;
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      } else {
        serviceApiIdOption.disabled = false;
      }

      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      if (list.length > 1) {
        const nowVal = list.shift();
        this.$refs.crud.toggleRowSelection(nowVal, false);
      }
      if (list.length > 0) {
        this.serviceConfigId = list[0].id;
        this.serviceApiId = list[0].serviceApiId;
      }
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
      this.serviceConfigId = undefined;
      this.serviceApiId = undefined;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      this.sort = {};
      if (func.notEmpty(val.order)) {
        if (val.order === 'ascending') {
          this.sort.ascs = func.cameCaseToLine(val.prop);
        } else {
          this.sort.descs = func.cameCaseToLine(val.prop);
        }
      }
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        serviceApiId,
        createUser,
        createTime,
        status
      } = Object.assign(params, this.query);

      let values = {
        serviceApiId_equal: serviceApiId,
        createUser_equal: createUser,
        createTime_datege: createTime ? createTime[0] : undefined,
        createTime_datelt: createTime ? createTime[1] : undefined,
        status_equal: status
      };

      getList(page.currentPage, page.pageSize, this.sort, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleMapping() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.mappingBox = true;
    },
    handlePrice() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '请求中,请稍后...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      priceApi(this.ids).then(res => {
        this.priceData = res.data.data;
        this.priceBox = true;
      }).finally(() => {
        loading.close();
      });
    },
    handleTop() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '请求中,请稍后...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      topApi(this.ids).then(res => {
        this.topData = res.data.data;
        this.topBox = true;
      }).finally(() => {
        loading.close();
      });
    },
    rowBalance(row) {
      const loading = this.$loading({
        lock: true,
        text: '请求中,请稍后...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      balanceApi(row.id).then(res => {
        row.balance = res.data.data;
      }).finally(() => {
        loading.close();
      });
    },
    rowTaskOption(row) {
      this.serviceConfigId = row.id;
      this.serviceApiId = row.serviceApiId;
      this.taskOptionBox = true;
    },
    rowMonitor(row){
      this.serviceConfigId = row.id;
      this.monitorBox = true;
    },
  }
};
</script>

<style>
</style>
